module Buffer (InsideAppend)
where

import Data.Maybe
import Engine

data InsideAppend 
	= Inside {left :: [String], cursor ::String , right :: [String]} 
	| Append { elems :: Either [String] [String]}
	deriving Show

instance Engine InsideAppend where
	listIn xs 				= Append (Right xs)
	prev (Append (Right _ )) 	= Nothing 
	prev (Append (Left [] )) 	= error "empty Append Left"
	prev (Append (Left (l:ls))) 	= Just $ Inside ls l [] 
	prev (Inside [] x ls) 		= Just $ Append (Right (x:ls)) 
	prev (Inside (l:ls) x rs) 	= Just $ Inside ls l (x:rs) 
	next (Append (Right [] )) 	= Nothing
	next (Append (Right (r:rs))) 	= Just $ Inside [] r rs 
	next (Append (Left [] )) 	= error "empty Append Left"
	next (Append (Left _ )) 	= Nothing
	next (Inside ls x [] ) 		= Just $ Append (Left (x:ls)) 
	next (Inside ls x (r:rs)) 	= Just $ Inside (x:ls) r rs 
	end w@ (Append (Left _)) 	= Just w
	end w 				= next w >>= end
	start w@ (Append (Right _)) 	= Just w
	start w 				= prev w >>= start 
	pos (Append (Left ls)) 		= End (length ls + 1)
	pos (Append (Right _)) 		= Begin
	pos (Inside ls _ _) 		= Line $ length ls + 1
	del (Append _) 			= Nothing
	del (Inside [] _ [] ) 		= Just $ Append (Right []) 
	del (Inside ls _ [] ) 		= Just $ Append (Left ls) 
	del (Inside ls _ (r:rs)) 	= Just $ Inside ls r rs
	deln n w 	| n == 0 		= Just w
		 	| True 		= del w >>= deln (n-1)
	add xs (Append (Left _ )) 	= Nothing
	add xs (Append (Right rs)) 	= Just $ Append $ Right (xs ++ rs)
	add xs (Inside ls x rs) 	= Just $ Inside ls x (xs ++ rs) 
	ins xs w 				= prev w >>= add xs 
	jump n w 				= start w >>= rjump n 
	listOut w 				= start w >>= \(Append (Right rs)) -> return rs
	values 0 _ 				= Just []
	values _ (Append _) 		= Nothing
	values n w@ (Inside _ x _ ) 	= next w >>= values (n - 1) >>= Just . (x:)
	


t = listIn ["paolo","va","in","bici"] :: InsideAppend
